import {storage} from "../../utils/common"
import router, {generateRouters} from "../../router/router"
import main from "@/page/main.vue"

const dynamicRoutes = {
    state: {
        routes: storage().get("routes") || []
    },
    getters: {
        generateRoutes(state) {
            return state.routes
        }
    },
    mutations: {
        generateRoutes(state, data) {
            if (!data) return
            storage().set('routes', data)
            let routes = {
                componentPath: "/main",
                path: "/",
                children: data,
                component: main,
                redirect: data[0].path
            }
            let routers = []
            generateRouters(routers, routes)
            routes.children = routers
            router.options.routes = [routes]
            router.addRoutes([routes])
            state.routes = data
        }
    },
    actions: {
        generateRoutes({commit}, data) {
            return new Promise(resolve => {
                commit('generateRoutes', data)
                resolve(true)
            })
        }
    }
}

export default dynamicRoutes
